package com.liukaixin.product.ru.data.repositories;

import android.support.annotation.NonNull;

import com.alibaba.fastjson.JSON;
import com.liukaixin.product.ru.AppController;
import com.liukaixin.product.ru.data.CallBackListener;
import com.liukaixin.product.ru.data.model.Apply;
import com.liukaixin.product.ru.data.model.Result;
import com.liukaixin.product.ru.data.model.Team;
import com.liukaixin.product.ru.data.model.TeamMember;
import com.liukaixin.product.ru.data.model.User;
import com.liukaixin.product.ru.data.model.UserTeam;
import com.liukaixin.product.ru.enumerate.ApplyStatusEnum;
import com.liukaixin.product.ru.enumerate.ResultTypeEnum;
import com.liukaixin.product.ru.service.ServiceFactory;
import com.liukaixin.product.ru.service.TeamsService;
import com.liukaixin.product.ru.util.ACache;
import com.orhanobut.logger.Logger;

import java.util.ArrayList;
import java.util.List;

import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

import static com.google.common.base.Preconditions.checkNotNull;

/**
 * Created by Jacob on 2016/9/5.
 */
public class TeamsRepository {

    private static TeamsRepository INSTANCE = null;
    private TeamsService teamsService;
    private ACache aCache = AppController.getInstance().getCache();

    private TeamsRepository() {

        this.teamsService = ServiceFactory
                .createRetrofitService(TeamsService
                        .class, ServiceFactory.BASE_URL);
    }

    public static TeamsRepository getInstance() {
        if (INSTANCE == null) {
            INSTANCE = new TeamsRepository();
        }
        return INSTANCE;
    }

    public static void destoryInstance() {
        INSTANCE = null;
    }

    /**
     * 发布状态的团队
     *
     * @param page     页码
     * @param rows     条数
     * @param callback 回调
     */

    public void getReleaseTeams(Integer page, Integer rows,
                                @NonNull
                                final CallBackListener<List<Team>> callback) {
        checkNotNull(callback);

        teamsService.getReleasedTeams(page, rows)
                .subscribeOn(Schedulers.newThread())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<Result<List<Team>>>() {
                    @Override
                    public void onCompleted() {
                        callback.onCompleted();
                    }

                    @Override
                    public void onError(Throwable e) {
                        Logger.e(e, e.getMessage());
                        callback.onError(e.getMessage());
                    }

                    @Override
                    public void onNext(Result<List<Team>> result) {
                        if (result.getCode().equals(Result.SUCCESS)) {
                            callback.onNext(result.getBean());
                        } else {
                            callback.onNext(new ArrayList<>());
                        }
                    }
                });
    }

    /**
     * 根据用户id获取团队列表.
     *
     * @param page     页码
     * @param rows     条数
     * @param callback 回调
     */
    public void getTeamsByUserId(final Integer page,
                                 final Integer rows,
                                 @NonNull
                                 final CallBackListener<List<UserTeam>> callback) {
        checkNotNull(callback);

        User user = JSON.parseObject(AppController.getInstance().getCache().getAsString("user"),
                User.class);

        teamsService.getTeamsByUserId(page, rows, user.getId())
                .subscribeOn(Schedulers.newThread())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<Result<List<UserTeam>>>() {
                    @Override
                    public void onCompleted() {
                        callback.onCompleted();
                    }

                    @Override
                    public void onError(Throwable e) {
                        Logger.e(e, e.getMessage());
                        callback.onError(e.getMessage());
                    }

                    @Override
                    public void onNext(Result<List<UserTeam>> result) {
                        if (result.getCode().equals(Result.SUCCESS)) {
                            callback.onNext(result.getBean());
                        } else {
                            callback.onError(result.getMessage());
                        }
                    }
                });
    }

    /**
     * 发送加入团队时的申请(我的特长)到服务器.
     *
     * @param apply    申请
     * @param callback 回调
     */
    public void sendAbility(Apply apply,
                            @NonNull
                            CallBackListener<String> callback) {
        checkNotNull(callback);

        teamsService.sendAbility(apply)
                .subscribeOn(Schedulers.newThread())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<Result<String>>() {
                    @Override
                    public void onCompleted() {
                        callback.onCompleted();
                    }

                    @Override
                    public void onError(Throwable e) {
                        Logger.e(e, e.getMessage());
                        callback.onError(e.getMessage());
                    }

                    @Override
                    public void onNext(Result<String> result) {
                        if (result.getCode().equals(Result.SUCCESS)) {
                            callback.onNext(result.getMessage());
                        } else {
                            callback.onError(result.getMessage());
                        }
                    }
                });
    }

    /**
     * 发送创建团队到服务器.
     *
     * @param team     团队
     * @param callback 回调
     */
    public void sendCreatedTeam(Team team,
                                @NonNull
                                CallBackListener<String> callback) {
        checkNotNull(callback);

        teamsService.sendCreatedTeam(team)
                .subscribeOn(Schedulers.newThread())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<Result<String>>() {
                    @Override
                    public void onCompleted() {
                        callback.onCompleted();
                    }

                    @Override
                    public void onError(Throwable e) {
                        Logger.e(e, e.getMessage());
                        callback.onError(e.getMessage());
                    }

                    @Override
                    public void onNext(Result<String> result) {
                        if (result.getCode().equals(Result.SUCCESS)) {
                            callback.onNext(result.getMessage());
                        } else {
                            callback.onError(result.getMessage());
                        }
                    }
                });
    }

    /**
     * 根据用户id获取团队成员详情.
     *
     * @param teamId   团队id
     * @param userId   用户id
     * @param callback 回调
     */
    public void getTeamMemberInfoByTeamIdAndUserId(
            Integer teamId,
            Integer userId,
            @NonNull
            CallBackListener<User> callback) {
        checkNotNull(callback);

        teamsService.getTeamMemberInfoByTeamIdAndUserId(teamId, userId)
                .subscribeOn(Schedulers.newThread())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<Result<User>>() {
                    @Override
                    public void onCompleted() {
                        callback.onCompleted();
                    }

                    @Override
                    public void onError(Throwable e) {
                        Logger.e(e, e.getMessage());
                        callback.onError(e.getMessage());
                    }

                    @Override
                    public void onNext(Result<User> result) {
                        if (result.getCode().equals(Result.SUCCESS)) {
                            callback.onNext(result.getBean());
                        } else {
                            callback.onError(result.getMessage());
                        }
                    }
                });
    }


    /**
     * 根据id获取团队详情.
     *
     * @param teamId   团队id
     * @param callback 回调
     */
    public void getTeamDescById(Integer teamId,
                                @NonNull CallBackListener<Team> callback) {

        checkNotNull(callback);

        teamsService.getTeamDescById(teamId)
                .subscribeOn(Schedulers.newThread())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<Result<Team>>() {
                    @Override
                    public void onCompleted() {
                        callback.onCompleted();
                    }

                    @Override
                    public void onError(Throwable e) {
                        Logger.e(e, e.getMessage());
                        callback.onError(e.getMessage());
                    }

                    @Override
                    public void onNext(Result<Team> result) {
                        if (result.getCode().equals(Result.SUCCESS)) {
                            callback.onNext(result.getBean());
                        } else {
                            callback.onError(result.getMessage());
                        }
                    }
                });
    }

    /**
     * 根据竞赛页码,条数,竞赛id获取团队列表.
     *
     * @param page          页码
     * @param rows          条数
     * @param competitionId 竞赛id
     * @param callback      回调
     */
    public void getTeamsByCompetitionId(Integer page, Integer rows,
                                        Integer competitionId,
                                        CallBackListener<List<Team>> callback) {
        checkNotNull(callback);

        teamsService.getTeamsByCompetitionId(page, rows, competitionId)
                .subscribeOn(Schedulers.newThread())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<Result<List<Team>>>() {
                    @Override
                    public void onCompleted() {
                        callback.onCompleted();
                    }

                    @Override
                    public void onError(Throwable e) {
                        Logger.e(e, e.getMessage());
                        callback.onError(e.getMessage());
                    }

                    @Override
                    public void onNext(Result<List<Team>> result) {
                        if (result.getCode().equals(Result.SUCCESS)) {
                            callback.onNext(result.getBean());
                        } else {
                            callback.onError(result.getMessage());
                        }
                    }
                });
    }

    /**
     * 获得是否申请过加入团队.
     *
     * @param teamId      团队id
     * @param applyUserId 申请人id
     * @param callback    回掉
     */
    public void getApplyStatus(Integer teamId, Integer applyUserId,
                               @NonNull
                              final CallBackListener<Integer> callback) {
        checkNotNull(callback);

        teamsService.getApplyStatus(teamId, applyUserId)
                .subscribeOn(Schedulers.newThread())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<Result<Integer>>() {
                    @Override
                    public void onCompleted() {
                        callback.onCompleted();
                    }

                    @Override
                    public void onError(Throwable e) {
                        Logger.e(e, e.getMessage());
                        callback.onError(e.getMessage());
                    }

                    @Override
                    public void onNext(Result<Integer> result) {
                        if (result.getCode().equals(Result.SUCCESS)) {
                            callback.onNext(result.getBean());
                        } else {
                            callback.onError(result.getMessage());
                        }
                    }
                });
    }

    public void getApplyById(Integer applyId,
                             @NonNull
                             final CallBackListener<Apply> callback) {
        checkNotNull(callback);

        teamsService.getApplyById(applyId)
                .subscribeOn(Schedulers.newThread())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<Result<Apply>>() {
                    @Override
                    public void onCompleted() {
                        callback.onCompleted();
                    }

                    @Override
                    public void onError(Throwable e) {
                        Logger.e(e, e.getMessage());
                        callback.onError(e.getMessage());
                    }

                    @Override
                    public void onNext(Result<Apply> result) {
                        if (result.getCode().equals(Result.SUCCESS)) {
                            callback.onNext(result.getBean());
                        } else {
                            callback.onError(result.getMessage());
                        }
                    }
                });
    }

    public void updateApplyStatus(Integer applyId,
                                  Integer status,
                                  @NonNull
                                  final CallBackListener<String> callback) {
        checkNotNull(callback);

        teamsService.updateApplyStatus(applyId, status)
                .subscribeOn(Schedulers.newThread())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<Result<String>>() {
                    @Override
                    public void onCompleted() {
                        callback.onCompleted();
                    }

                    @Override
                    public void onError(Throwable e) {
                        Logger.e(e, e.getMessage());
                        callback.onError(e.getMessage());
                    }

                    @Override
                    public void onNext(Result<String> result) {
                        if (result.getCode().equals(Result.SUCCESS)) {
                            if (status.equals(ApplyStatusEnum.AGREE.getTypeCode())) {
                                callback.onNext("您已同意申请");
                            } else {
                                callback.onNext("您已拒绝申请");
                            }
                        } else {
                            callback.onError(result.getMessage());
                        }
                    }
                });
    }

    public void addToMyTeam(@NonNull UserTeam userTeam) {
        checkNotNull(userTeam);

        teamsService.addToMyTeam(userTeam)
                .subscribeOn(Schedulers.newThread())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<Result<String>>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        Logger.e(e, e.getMessage());
                    }

                    @Override
                    public void onNext(Result<String> result) {

                    }
                });
    }

    public void getOtherApplyStatus(@NonNull Integer applyUserId,
                                    @NonNull String competitionName,
                                    @NonNull CallBackListener<Integer> callback) {
        checkNotNull(applyUserId);
        checkNotNull(competitionName);
        checkNotNull(callback);

        teamsService.getOtherApplyStatus(applyUserId, competitionName)
                .subscribeOn(Schedulers.newThread())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<Result<Integer>>() {
                    @Override
                    public void onCompleted() {
                        // do nothing
                    }

                    @Override
                    public void onError(Throwable e) {
                        Logger.e(e, e.getMessage());
                        callback.onError(e.getMessage());
                    }

                    @Override
                    public void onNext(Result<Integer> result) {
                        if (result.getCode().equals(ResultTypeEnum.SUCCESS.getValue())) {
                            callback.onNext(result.getBean());
                        } else {
                            callback.onError(result.getMessage());
                        }
                    }
                });
    }

    public void getMyAppliesByUserId(@NonNull Integer page,
                                     @NonNull Integer rows,
                                     @NonNull
                                     final CallBackListener<List<Apply>> callback) {
        checkNotNull(callback);

        User user = JSON.parseObject(AppController.getInstance().getCache().getAsString("user"),
                User.class);

        teamsService.getMyAppliesByUserId(page, rows, user.getId())
                .subscribeOn(Schedulers.newThread())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<Result<List<Apply>>>() {
                    @Override
                    public void onCompleted() {
                        // do nothing
                    }

                    @Override
                    public void onError(Throwable e) {
                        Logger.e(e, e.getMessage());
                        callback.onError(e.getMessage());
                    }

                    @Override
                    public void onNext(Result<List<Apply>> result) {
                        if (result.getCode().equals(ResultTypeEnum.SUCCESS.getValue())) {
                            callback.onNext(result.getBean());
                        } else {
                            callback.onError(result.getMessage());
                        }
                    }
                });
    }

    public void getTeamMembers(@NonNull Integer teamId,
                               @NonNull
                               final CallBackListener<List<TeamMember>> callback) {
        checkNotNull(callback);

        teamsService.getTeamMembers(teamId)
                .subscribeOn(Schedulers.newThread())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<Result<List<TeamMember>>>() {
                    @Override
                    public void onCompleted() {
                        // do nothing
                    }

                    @Override
                    public void onError(Throwable e) {
                        Logger.e(e, e.getMessage());
                        callback.onError(e.getMessage());
                    }

                    @Override
                    public void onNext(Result<List<TeamMember>> result) {
                        if (result.getCode().equals(ResultTypeEnum.SUCCESS.getValue())) {
                            callback.onNext(result.getBean());
                        } else {
                            callback.onError(result.getMessage());
                        }
                    }
                });
    }
}
